<template>
  <a-layout class="con">
    <a-layout-sider class="sider">
      <div style="height: 35px">
        <a-input-search @clear="getExpressProList" @search="getExpressProList" v-model="expressSearchValue.expressOrProviderName" allow-clear placeholder="物流账号或服务商名称" :style="{ width: '190px' }" />
        <a-button class="gray-outline" style="margin-left: 5px" @click="showAccountModel('add')" v-if="$authPass('express.provider.saveOrUpdate')">添加</a-button>
      </div>

      <a-scrollbar style="height: calc(100vh - 145px); overflow-y: auto">
        <div class="account-list">
          <ul>
            <li v-for="(item, index) of expressProviderList" :key="item.id" @click="checkExpress(index)" :class="[currentIndex == index ? 'active' : '']">
              <div class="top">
                <!-- <div>{{ item.expressName }}({{ item.providerCode }})</div> -->
                <div>{{ item.expressName }}<icon-edit v-if="$authPass('express.provider.saveOrUpdate')" style="margin-left: 10px" @click.stop="showAccountModel('edit', item)" /></div>
                <div v-if="item.isAuthExpired" style="color: #f59a23">
                  <span class="icon icon-zhuyi"></span>
                  <span>授权过期</span>
                </div>
                <div style="color: darkgray">
                  {{ item.providerType == 'custom' ? '自定义' : 'API' }}
                </div>
              </div>
              <div class="bottom">
                <a-popover>
                  <div style="color: darkgray; width: 120px" class="text-limit">{{ item.providerName }}({{ item.providerCode }})</div>
                  <template #content>
                    <p>{{ item.providerName }}({{ item.providerCode }})</p>
                  </template>
                </a-popover>

                <div style="color: darkgray">{{ $setTime(item.gmtCreate) }}</div>
              </div>
            </li>
          </ul>
        </div>
      </a-scrollbar>
    </a-layout-sider>
    <a-layout-content class="content table-gl-w">
      <div class="search-con search-w">
        <FilterTable :filterItem="providerInfo.providerType == 'api' ? apiFilterItem : customFilterItem" :isReset="true" @search="searchByVal" />
      </div>
      <div class="table-gl-con">
        <TableWrap style="flex: 1" @refresh="sizeChange(20)">
          <template #headerLeft>
            <a-button class="gray-outline" @click="showProviderChannel('add')" v-if="providerInfo.providerType == 'custom' && $authPass('express.channel.saveOrUpdate')">添加渠道</a-button>
            <a-button class="gray-outline" style="margin-left: 10px" @click="del('mul')" v-if="providerInfo.providerType == 'custom' && $authPass('express.channel.del')">删除渠道</a-button>
            <a-button class="gray-outline" style="margin-left: 10px" v-if="providerInfo.providerType == 'api' && $authPass('express.channel.sync')" :loading="syncChannelLoading" @click="syncChannel">同步渠道</a-button>
            <a-button class="gray-outline" style="margin-left: 10px" v-if="providerInfo.providerType == 'api' && $authPass('express.channel.updateStatus')" @click="editSatus(true, 'mul')">批量启用</a-button>
            <a-button class="gray-outline" style="margin-left: 10px" v-if="providerInfo.providerType == 'api' && $authPass('express.channel.updateStatus')" @click="editSatus(false, 'mul')">批量停用</a-button>
          </template>
          <template #tableBody>
            <a-table size="mini" class="table-singe-line show-border-table" ref="table" :loading="loading" row-key="id" v-model:selected-keys="rowSelectList" :row-selection="rowSelection" :data="tableList" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
              <template #columns>
                <a-table-column title="序号" #cell="{ record, rowIndex }" :width="40">
                  {{ rowIndex + 1 }}
                </a-table-column>
                <a-table-column title="渠道名称" #cell="{ record, rowIndex }" :width="80">
                  {{ record.name }}
                </a-table-column>
                <a-table-column title="渠道代码" #cell="{ record, rowIndex }" :width="80">
                  {{ record.code }}
                </a-table-column>
                <a-table-column title="创建人" #cell="{ record, rowIndex }" :width="80" v-if="providerInfo.providerType == 'custom'">
                  {{ record.createUname }}
                </a-table-column>
                <a-table-column title="创建时间" #cell="{ record, rowIndex }" :width="140" v-if="providerInfo.providerType == 'custom'">
                  {{ $setTime(record.gmtCreate) }}
                </a-table-column>
                <a-table-column title="状态" #cell="{ record, rowIndex }" :width="60" v-if="providerInfo.providerType == 'api'">
                  <a-switch v-model="record.enable" :disabled="!$authPass('express.channel.updateStatus')" @change="editSatus($event, 'single', record)">
                    <template #checked> 开 </template>
                    <template #unchecked> 关 </template>
                  </a-switch>
                </a-table-column>
                <a-table-column title="货运时效" #cell="{ record, rowIndex }" :width="80">
                  <span>{{ $extract(record, 'shipAging.startDay') }} - {{ $extract(record, 'shipAging.endDay') }}天</span>
                </a-table-column>
                <a-table-column title="亚马逊标发" #cell="{ record, rowIndex }" :width="100">
                  <div>{{ $extract(record, 'feedConfigList.carrier') }}</div>
                  <div>{{ $extract(record, 'feedConfigList.shippingMethod') }}</div>
                  <div>{{ $extract(record, 'feedConfigList.shopType') }}</div>
                  <div>{{ $extract(record, 'feedConfigList.trackNumberType') }}</div>
                </a-table-column>
                <a-table-column title="面单规格" #cell="{ record, rowIndex }" :width="140">
                  <span>{{ record.labelSize }}</span>
                </a-table-column>
                <a-table-column title="运费模板" #cell="{ record, rowIndex }" :width="140">
                  {{ $extract(record, 'shipAmountTemplate.name') }}
                </a-table-column>
                <a-table-column title="操作" #cell="{ record, rowIndex }" :width="60">
                  <a-button type="text" @click="showProviderChannel('set', record)" v-if="$authPass('express.channel.saveOrUpdate')">设置</a-button>
                </a-table-column>
              </template>
            </a-table>
          </template>
        </TableWrap>
        <div class="pagination-footer">
          <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
        </div>
      </div>
    </a-layout-content>
  </a-layout>

  <AddExpressAccount ref="addExpressAccount" :type="accoutType" :detailInfo="accountDetailInfo" @save="getExpressProList" />
  <AddExpressChannel ref="expressChannel" :info="providerInfo" :type="type" :detailInfo="detailInfo" @save="sizeChange(20)" />
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs } from 'vue'
  import { listExpressProvider, pageExpressChannel, updateStatusExpressChannel, delExpressChannels, syncChannels } from '@/api/warehouse'
  import { getOrganizesUser } from '@/api/system'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import AddExpressAccount from './components/addExpressAccount.vue'
  import AddExpressChannel from './components/addExpressChannel.vue'
  import { Modal, Message } from '@arco-design/web-vue'

  export default defineComponent({
    components: { AddExpressAccount, FilterTable, TableWrap, AddExpressChannel },
    setup() {
      const addExpressAccount = ref()
      const expressChannel = ref()
      const data: any = reactive({
        expressSearchValue: {
          expressOrProviderName: '',
        },
        currentIndex: 0,
        expressProviderList: [],
        apiFilterItem: [
          {
            type: 'input_keyword',
            key: 'name',
            keyItems: [
              { label: '渠道名称', value: 'name' },
              { label: '渠道代码', value: 'code' },
            ],
            keyWidth: '120',
            value: ref(),
            placeholder: '请输入',
            label: '渠道名称',
            width: 160,
            isMultiple: false,
          },
          {
            type: 'select',
            key: 'enable',
            keyWidth: '90',
            optionItems: [
              { label: '启用', value: true },
              { label: '停用', value: false },
            ],
            value: ref(),
            placeholder: '状态',
            label: '创建人',
            width: 80,
          },
        ],
        customFilterItem: [
          {
            type: 'input_keyword',
            key: 'name',
            keyItems: [
              { label: '渠道名称', value: 'name' },
              { label: '渠道代码', value: 'code' },
            ],
            keyWidth: '120',
            value: ref(),
            placeholder: '请输入',
            label: '渠道名称',
            width: 160,
            isMultiple: false,
          },
          {
            type: 'select',
            key: 'createUid',
            keyWidth: '90',
            optionItems: [],
            value: ref(),
            placeholder: '请选择创建人',
            label: '创建人',
            width: 160,
            isMultiple: false,
            attrs: {
              'allow-search': true,
            },
          },
          {
            type: 'keyword_date_range',
            key: 'gmtCreate',
            keyItems: [
              { label: '创建日期', value: 'gmtCreate' },
              // { label: '审核日期', value: 'gmtAudit' },
            ],
            keyWidth: '110',
            value: ref(),
            placeholder: '请输入',
            label: '创建日期',
            width: 200,
          },
        ],
        tableList: [],
        pageNation: { total: 0, pageSize: 20, pageNum: 1 },
        loading: false,
        rowSelectList: [],
        rowSelection: {
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false,
        },
        searchValue: {},
        providerInfo: {},
        type: 'add',
        detailInfo: {},
        accoutType: '',
        accountDetailInfo: {},
        syncChannelLoading: false,
      })

      const checkExpress = (index: number) => {
        data.currentIndex = index
        data.pageNation.pageNum = 1
        data.providerInfo = data.expressProviderList[data.currentIndex]
        data.searchValue = {}
        getList()
      }

      const getExpressProList = async () => {
        data.currentIndex = 0
        const res = await listExpressProvider(data.expressSearchValue)
        data.expressProviderList = res?.data || []
        data.providerInfo = data.expressProviderList[data.currentIndex]
        console.log(data.providerInfo.providerType)

        getList()
      }

      const changePage = (val: number) => {
        data.pageNation.pageNum = val
        getList()
      }

      const sizeChange = (val: number) => {
        data.pageNation.pageNum = 1
        data.pageNation.pageSize = val
        getList()
      }

      const getList = async (info?: any) => {
        console.log(data.searchValue)

        let params = {
          expressProviderId: data.expressProviderList[data.currentIndex].id,
          ...data.searchValue,
          pageNum: data.pageNation.pageNum,
          pageSize: data.pageNation.pageSize,
        }
        data.loading = true
        const res: any = await pageExpressChannel(params)
        if (res.code == 'SUCCESS') {
          data.tableList = res.data?.records || []
          data.pageNation.total = res.data.total
        }
        data.loading = false
      }

      // 获取用户列表
      const getUSerList = async () => {
        let params = {
          depart: false,
          pageNum: 1,
          pageSize: 1000,
        }
        const res: any = await getOrganizesUser(params)
        if (res.code == 'SUCCESS') {
          let userList = res.data.records
          userList.map((e: any) => {
            e.label = e.userName
            e.value = e.id
            return e
          })
          data.customFilterItem[1].optionItems = userList
        }
      }

      const showProviderChannel = (type: string, info: any) => {
        if (info) data.detailInfo = info
        data.type = type
        data.providerInfo = data.expressProviderList[data.currentIndex]
        expressChannel.value.visible = true
      }

      const del = (type: string) => {
        if (type == 'mul') {
          if (data.rowSelectList.length <= 0) {
            return Message.error('请先选择需要删除的数据')
          }
          Modal.error({
            title: '提示',
            content: '是否删除？',
            titleAlign: 'start',
            cancelText: '取消',
            hideCancel: false,
            onBeforeOk: async (done) => {
              const res: any = await delExpressChannels({ idList: data.rowSelectList })
              if (res.code == 'SUCCESS') {
                done(true)
                Message.success('删除成功')
                getList()
              }
            },
          })
        }
      }

      const editSatus = async (val: boolean, type: string, info?: any) => {
        let params: any = {
          idList: [],
          enable: val,
        }
        if (type == 'mul') {
          if (data.rowSelectList.length <= 0) {
            return Message.error('请先选择需要修改状态的数据')
          }
          params.idList = data.rowSelectList
        } else {
          params.idList.push(info.id)
        }

        const res: any = await updateStatusExpressChannel(params)
        if (res.code == 'SUCCESS') {
          Message.success('修改成功')
          data.rowSelectList = []
          getList()
        }
      }

      const searchByVal = (info: any) => {
        data.searchValue = {}
        data.searchValue = info

        data.pageNation.pageNum = 1
        if (data.searchValue.startDate) {
          data.searchValue.startDate = `${data.searchValue.startDate} 00:00:00`
          data.searchValue.endDate = `${data.searchValue.endDate} 23:59:59`
        }
        getList()
      }

      const showAccountModel = (type: string, item: any) => {
        data.accoutType = type
        data.accountDetailInfo = item
        addExpressAccount.value.visible = true
      }

      const syncChannel = async () => {
        data.syncChannelLoading = true
        try {
          const res: any = await syncChannels({ expressProviderId: data.providerInfo.id })
          if (res.code == 'SUCCESS') {
            Message.success('同步成功')
          }
          getList()
          data.syncChannelLoading = false
        } catch (error) {
          data.syncChannelLoading = false
        }
      }

      getExpressProList()
      getUSerList()
      return {
        ...(toRefs(data) as any),
        checkExpress,
        getExpressProList,
        addExpressAccount,
        changePage,
        sizeChange,
        expressChannel,
        showProviderChannel,
        del,
        editSatus,
        searchByVal,
        showAccountModel,
        syncChannel,
      }
    },
  })
</script>

<style lang="less" scoped>
  .con {
    height: 100%;
    padding: 5px;
    .sider {
      width: 260px !important;
      height: calc(100vh - @menuHeight - 10px);
      padding: 5px;
      overflow: hidden;
    }
    .content {
      margin-left: 5px;
      height: calc(100vh - @menuHeight - 10px);
      // background-color: white;
    }

    .account-list {
      ul {
        li {
          width: 100%;
          height: 52px;
          padding: 2px 3px;
          font-size: 12px;
          margin-top: 10px;
          user-select: none;

          background-color: var(--color-neutral-1);
          &:hover {
            background-color: #e5e6eb;
          }

          .top {
            width: 100%;
            height: 24px;
            display: flex;
            justify-content: space-between;
          }

          .bottom {
            width: 100%;
            height: 24px;
            line-height: 24px;
            display: flex;
            justify-content: space-between;
          }
        }

        .active {
          background-color: #e5e6eb;
        }
      }
    }
  }
</style>
